package com.leetcode.offer.chapter4;


/**
 * @author Dennis Li
 * @date 2020/7/13 16:27
 */
public class SpiralOrder_29 {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0) return new int[0];
        int r = matrix.length - 1, b = matrix[0].length - 1, l = 0, t = 0;
        int x = 0;
        int[] nums = new int[(r + 1) * (b + 1)];
        while (true) {
            for (int i = l; i <= r; i++) nums[x++] = matrix[t][i];
            if(++t > b) break;
            for (int i = t; i <= b; i++) nums[x++] = matrix[i][r];
            if(l > --r) break;
            for (int i = r; i >= l; i--) nums[x++] = matrix[b][i];
            if(t > --b) break;
            for (int i = b; i >= t; i--) nums[x++] = matrix[i][t];
            if(++l > r) break;
        }
        return nums;
    }
}
